package com.wl156.activities.publish;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wl156.BaseActivity;
import com.wl156.MyApp;
import com.wl156.R;
import com.wl156.activities.AddCar;
import com.wl156.model.Certificate;
import com.wl156.model.User;
import com.wl156.model.WebServiceClient;
import com.wl156.utils.Utils;
import com.wl156.widget.ProviceSelector;

public class NewCarInfo extends BaseActivity implements OnClickListener {
	private static final String TAG = null;
	RelativeLayout mFutureLayout;
	TextView mCarCode;
	TextView mCarModel;
	TextView mCarWeight;
	TextView mCarLength;
	TextView mContact;
	TextView mPhone;

	EditText mNeed;
	EditText mOfenRunLine;
	TextView mDateShow;
	private EditText mComment;

	private ProviceSelector mFromProviceSelector;
	private ProviceSelector mToProviceSelector;

	WebServiceClient mWebServiceClient;
	Certificate mCertificate;

	boolean isCompany = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Window win = getWindow();
		// win.requestFeature(Window.FEATURE_LEFT_ICON);
		setContentView(R.layout.act_new_car_info);
		// win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
		// R.drawable.ic_launcher);

		mWebServiceClient = new WebServiceClient(this);
		mCertificate = ((MyApp) getApplication()).getCertificateFromXml();

		Button confirm = (Button) findViewById(R.id.confirm);
		confirm.setOnClickListener(this);
		mFromProviceSelector = (ProviceSelector) findViewById(R.id.provice_selector);
		mFromProviceSelector.setTitle("起点: ");
		mFromProviceSelector.setProviceRequried(true);
		mFromProviceSelector.setCityRequried(true);
		mToProviceSelector = (ProviceSelector) findViewById(R.id.to_provice_selector);
		mToProviceSelector.setTitle("终点: ");
		mToProviceSelector.setProviceRequried(true);
		mToProviceSelector.setCityRequried(true);

		mComment = (EditText) findViewById(R.id.comment);
		mCarCode = (TextView) findViewById(R.id.car_code);
		mCarModel = (TextView) findViewById(R.id.car_model);
		mCarWeight = (TextView) findViewById(R.id.weight);
		mCarLength = (TextView) findViewById(R.id.length);
		mContact = (TextView) findViewById(R.id.contact);
		mPhone = (TextView) findViewById(R.id.phone);
		mFutureLayout = (RelativeLayout) findViewById(R.id.future_layout);
		mDateShow = (TextView) findViewById(R.id.date_show);
		CheckBox futureCheck = (CheckBox) findViewById(R.id.check_future_info);
		futureCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				mFutureLayout.setVisibility(isChecked ? View.VISIBLE
						: View.GONE);
			}
		});
		Button selectDate = (Button) findViewById(R.id.select_date);
		selectDate.setOnClickListener(this);

		User user = ((MyApp) getApplication()).getCurrentUser();
		mContact.setText(user.name);
		mPhone.setText(user.phone);
		Log.d("NewCarInfo", user.type);
		if (user.type.equals("C")) {
			isCompany = true;
		}

		new GetNewCarInfo().execute();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {
			new GetNewCarInfo().execute();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirm:
			final String startLocationLv1 = mFromProviceSelector.getProvice();
			final String startLocationLv2 = mFromProviceSelector.getCity();
			final String startLocationLv3 = mFromProviceSelector.getRegion();
			final String endLocationLv1 = mToProviceSelector.getProvice();
			final String endLocationLv2 = mToProviceSelector.getCity();
			final String endLocationLv3 = mToProviceSelector.getRegion();
			final String comment = mComment.getText().toString();
			final String date = mDateShow.getText().toString();

			if (TextUtils.isEmpty(startLocationLv1)
					|| TextUtils.isEmpty(startLocationLv2)) {
				Toast.makeText(NewCarInfo.this, "请填写相应字段", Toast.LENGTH_LONG)
						.show();
				return;
			}

			new AsyncTask<Void, Void, Object>() {
				ProgressDialog mDialog;

				@Override
				protected void onPostExecute(Object result) {
					if (result instanceof SoapPrimitive) {
						SoapPrimitive sp = (SoapPrimitive) result;
						try {
							Integer.valueOf(sp.toString());
							Toast.makeText(NewCarInfo.this, "发布成功",
									Toast.LENGTH_LONG).show();

							Intent i = new Intent(NewCarInfo.this,
									NewCarInfoAfter.class);
							i.putExtra("startLocationLv1", startLocationLv1);
							i.putExtra("startLocationLv2", startLocationLv2);
							i.putExtra("startLocationLv3", startLocationLv3);
							i.putExtra("endLocationLv1", endLocationLv1);
							i.putExtra("endLocationLv2", endLocationLv2);
							i.putExtra("endLocationLv3", endLocationLv3);
							i.putExtra("comment", comment);
							i.putExtra("date", date);
							startActivity(i);
							finish();
						} catch (Exception e) {
							Toast.makeText(NewCarInfo.this, sp.toString(),
									Toast.LENGTH_LONG).show();
						}
					} else {
						Toast.makeText(NewCarInfo.this, "发布失败，请稍候重试",
								Toast.LENGTH_LONG).show();
					}
					mDialog.dismiss();
				};

				@Override
				protected void onPreExecute() {
					mDialog = ProgressDialog.show(NewCarInfo.this, "", "发布中");
				};

				@Override
				protected Object doInBackground(Void... params) {
					try {
						return mWebServiceClient.driverPublishTrunckMessage(
								mCertificate, startLocationLv1,
								startLocationLv2, startLocationLv3,
								endLocationLv1, endLocationLv2, endLocationLv3,
								comment, date);
					} catch (IOException e) {
						return e;
					} catch (XmlPullParserException e) {
						return e;
					} catch (ParseException e) {
						return e;
					}
				}
			}.execute();
			break;
		case R.id.select_date:
			Calendar c = Calendar.getInstance();
			int year = c.get(Calendar.YEAR);
			int monthOfYear = c.get(Calendar.MONTH);
			int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);

			DatePickerDialog datePicker = new DatePickerDialog(this,
					new OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							Date date = new Date(year - 1900, monthOfYear,
									dayOfMonth);
							if (date.getTime() < System.currentTimeMillis()) {
								Toast.makeText(NewCarInfo.this, "选择日期小于当前日期",
										Toast.LENGTH_SHORT).show();
								return;
							}
							mDateShow.setText(sDateFormat.format(date));
						}
					}, year, monthOfYear, dayOfMonth);
			datePicker.show();
			break;
		}
	}

	class GetNewCarInfo extends AsyncTask<Void, Void, Object> {

		ProgressDialog mDialog;

		@Override
		protected void onPreExecute() {
			mDialog = ProgressDialog.show(NewCarInfo.this, "", "加载中");
		};

		@Override
		protected void onPostExecute(Object result) {
			try {
				if (result instanceof Object[]) {
					if (isCompany) {
						Object[] values = (Object[]) result;
						if (values[0] == null) {
							return;
						}
						SoapObject myCurrentPlace = (SoapObject) values[1];
						String lv1 = myCurrentPlace.getProperty(0).toString();
						String lv2 = myCurrentPlace.getProperty(1).toString();
						String lv3 = myCurrentPlace.getProperty(2).toString();
						mFromProviceSelector.setProvice(lv1);
						mFromProviceSelector.setCity(lv2);
						mFromProviceSelector.setRegion(lv3);

						try {
							// 06-08 12:33:44.957: D/(28247): result:
							// anyType{ArrayOfString=anyType{string=61;
							// string=G33885; string=太蓬车; string=34; string=12;
							// string=林琪; string=13543883997; string=运冰块; };
							// ArrayOfString=anyType{string=21; string=粤C76534;
							// string=其它; string=21; string=121; string=何生;
							// string=1345667881; string=食品，冷藏; };
							// ArrayOfString=anyType{string=1; string=粤C8888;
							// string=自卸车; string=24; string=243; string=sadf;
							// string=sdf; string=24; }; }, type: SoapObject

							// /// 货车ID
							// / 车牌号
							// / 车型
							// / 吨位
							// / 车长
							// / 联系人
							// / 电话
							// / 货运需求

							final SoapObject cars = (SoapObject) values[0];
							String[] items = new String[(cars
									.getPropertyCount() >= 1 ? 1 : 0)];
							for (int i = 0; i < (cars.getPropertyCount() >= 1 ? 1
									: 0); i++) {
								SoapObject item = (SoapObject) cars
										.getProperty(i);
								items[i] = String.format("%s, %s", Utils
										.propertyToShow(item.getProperty(1)),
										Utils.propertyToShow(item
												.getProperty(5)));
								Log.d(TAG, "items[i]: " + items[i]);
							}
							AlertDialog.Builder builder = new Builder(
									NewCarInfo.this);
							builder.setTitle("选择车辆");
							builder.setItems(items,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											SoapObject item = (SoapObject) cars
													.getProperty(which);
											mCarCode.setText(Utils
													.propertyToShow(item
															.getProperty(1)));
											mCarModel.setText(Utils
													.propertyToShow(item
															.getProperty(2)));
											mCarWeight.setText(Utils
													.propertyToShow(item
															.getProperty(3)));
											mCarLength.setText(Utils
													.propertyToShow(item
															.getProperty(4)));
											mContact.setText(Utils
													.propertyToShow(item
															.getProperty(5)));
											mPhone.setText(Utils
													.propertyToShow(item
															.getProperty(6)));
										}
									});
							builder.show();
						} catch (Exception e) {
							Log.d(TAG, "没车");

							Intent i = new Intent(NewCarInfo.this, AddCar.class);
							startActivityForResult(i, 0);
							Toast.makeText(NewCarInfo.this, "资料未完善，请完善",
									Toast.LENGTH_LONG).show();
						}
					} else {
						Object[] values = (Object[]) result;
						if (values[0] != null) {
							try {
								SoapObject myTruck = (SoapObject) values[0];
								String carCode = Utils.propertyToShow(myTruck
										.getProperty(0));
								String carType = Utils.propertyToShow(myTruck
										.getProperty(1));
								String carWeight = Utils.propertyToShow(myTruck
										.getProperty(2));
								String carLength = Utils.propertyToShow(myTruck
										.getProperty(3));
								String contact = Utils.propertyToShow(myTruck
										.getProperty(4));
								String phone = Utils.propertyToShow(myTruck
										.getProperty(5));
								String need = Utils.propertyToShow(myTruck
										.getProperty(6));
								mCarCode.setText(carCode);
								mCarModel.setText(carType);
								mCarLength.setText(carLength);
								mCarWeight.setText(carWeight);
								mContact.setText(contact);
								mPhone.setText(phone);
								// mComment.setText(need);
							} catch (Exception e) {
								e.printStackTrace();
								Log.d(TAG, "没车");

								Intent i = new Intent(NewCarInfo.this,
										AddCar.class);
								startActivityForResult(i, 0);
								Toast.makeText(NewCarInfo.this, "资料未完善，请完善",
										Toast.LENGTH_LONG).show();
							}
						} else {
							Log.d(TAG, "没车 + values[0] == null");

							Intent i = new Intent(NewCarInfo.this, AddCar.class);
							startActivityForResult(i, 0);
							Toast.makeText(NewCarInfo.this, "资料未完善，请完善",
									Toast.LENGTH_LONG).show();
						}

						SoapObject myCurrentPlace = (SoapObject) values[1];
						String lv1 = myCurrentPlace.getProperty(0).toString();
						String lv2 = myCurrentPlace.getProperty(1).toString();
						String lv3 = myCurrentPlace.getProperty(2).toString();
						mFromProviceSelector.setProvice(lv1);
						mFromProviceSelector.setCity(lv2);
						mFromProviceSelector.setRegion(lv3);
					}
				} else {
					AlertDialog.Builder builder = new Builder(NewCarInfo.this);
					builder.setMessage("网络请求超时！");
					builder.setPositiveButton("重试",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									new GetNewCarInfo().execute();
								}
							});
					builder.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							});
					builder.show();
				}

				mDialog.dismiss();
			} catch (Exception e) {
				e.printStackTrace();
			}
		};

		@Override
		protected Object doInBackground(Void... params) {
			if (isCompany) {
				Object[] values = new Object[2];
				try {
					values[0] = mWebServiceClient.company_getMyTruck(
							mCertificate, "", "", "");
					values[1] = mWebServiceClient
							.commonGetMyCurrentPlace(mCertificate);
					return values;
				} catch (IOException e) {
					e.printStackTrace();
					return e;
				} catch (XmlPullParserException e) {
					e.printStackTrace();
					return e;
				}
			} else {
				Object[] values = new Object[2];
				try {
					values[0] = mWebServiceClient
							.driverGetMyTruck(mCertificate);
					values[1] = mWebServiceClient
							.commonGetMyCurrentPlace(mCertificate);
					return values;
				} catch (IOException e) {
					e.printStackTrace();
					return e;
				} catch (XmlPullParserException e) {
					e.printStackTrace();
					return e;
				} catch (Exception e) {
					e.printStackTrace();
					return e;
				}
			}
		}
	}

	SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
